import { pythonGenerator, Order } from 'blockly/python'

// 判断字符串是否为整数
function isInteger(str) {
  return /^\d+$/.test(str)
}

// 生成无限循环代码
pythonGenerator.forBlock['controls_forever'] = function (block, generator) {
  const branch = generator.statementToCode(block, 'DO')
  return 'while True:\n' + branch
}

// 生成判断是否整除的代码
pythonGenerator.forBlock['math_evenly_divisible'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'DIVIDEND', Order.NONE) || '0'
  const argument2 = generator.valueToCode(block, 'DIVISOR', Order.NONE) || '1'
  return [argument1 + ' % ' + argument2 + ' == 0', Order.NONE]
}

// 生成获取字符串中某个字符的代码
pythonGenerator.forBlock['text_charAt'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"
  let argument2 = generator.valueToCode(block, 'AT', Order.NONE) || '1'
  if (block.getFieldValue('WHERE') === 'FROM_START') {
    argument2 = isInteger(argument2) ? Number(argument2) - 1 : argument2 + ' - 1'
  } else if (block.getFieldValue('WHERE') === 'FROM_END') {
    argument2 = argument1 + '.length - ' + argument2
  }
  return [argument1 + '[' + argument2 + ']', Order.NONE]
}

// 生成获取字符串中某个子串的代码
pythonGenerator.forBlock['text_getSubstring'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'STRING', Order.NONE) || "''"
  let argument2 = generator.valueToCode(block, 'WHERE1', Order.NONE) || '1'
  let argument3 = generator.valueToCode(block, 'WHERE2', Order.NONE) || '1'
  if (block.getFieldValue('WHERE1') === 'FROM_START') {
    argument2 = isInteger(argument2) ? Number(argument2) - 1 : argument2 + ' - 1'
  } else if (block.getFieldValue('WHERE1') === 'FROM_END') {
    argument2 = argument1 + '.length - ' + argument2
  }
  if (block.getFieldValue('WHERE2') === 'FROM_END') {
    argument3 = isInteger(argument3) ? Number(argument3) - 1 : argument3 + ' - 1'
    argument3 = argument1 + '.length - ' + argument3
  }
  return [argument1 + '[' + argument2 + ':' + argument3 + ']', Order.NONE]
}

// 生成类型转换的代码
pythonGenerator.forBlock['math_types'] = function (block, generator) {
  const map = { STRING: 'str', NUMBER: 'float', BOOLEAN: 'bool' }
  const argument1 = generator.valueToCode(block, 'VALUE', Order.NONE) || ''
  return [map[block.getFieldValue('TYPE')] + '(' + argument1 + ')', Order.NONE]
}

// 生成向列表中添加元素的代码
pythonGenerator.forBlock['lists_push'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'ITEM', Order.NONE) || ''
  const argument2 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  return argument2 + '.append(' + argument1 + ')'
}

// 生成向列表中插入元素的代码
pythonGenerator.forBlock['lists_insert'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None'
  const argument2 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  let argument3 = generator.valueToCode(block, 'AT', Order.NONE) || '1'
  if (block.getFieldValue('WHERE') === 'FROM_START') {
    argument3 = isInteger(argument3) ? Number(argument3) - 1 : argument3 + ' - 1'
  } else if (block.getFieldValue('WHERE') === 'FROM_END') {
    argument3 = argument2 + '.length - ' + argument3
  }
  return argument2 + '.insert(' + argument3 + ', ' + argument1 + ')'
}

// 生成从列表中删除元素的代码
pythonGenerator.forBlock['lists_delete'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  let argument2 = generator.valueToCode(block, 'AT', Order.NONE) || '1'
  if (block.getFieldValue('WHERE') === 'FROM_START') {
    argument2 = isInteger(argument2) ? Number(argument2) - 1 : argument2 + ' - 1'
  } else if (block.getFieldValue('WHERE') === 'FROM_END') {
    argument2 = argument1 + '.length - ' + argument2
  }
  return argument1 + '.pop(' + argument2 + ')'
}

// 生成设置列表中某个元素的代码
pythonGenerator.forBlock['lists_set'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  const argument3 = generator.valueToCode(block, 'TO', Order.NONE) || 'None'
  let argument2 = generator.valueToCode(block, 'AT', Order.NONE) || '1'
  if (block.getFieldValue('WHERE') === 'FROM_START') {
    argument2 = isInteger(argument2) ? Number(argument2) - 1 : argument2 + ' - 1'
  } else if (block.getFieldValue('WHERE') === 'FROM_END') {
    argument2 = argument1 + '.length - ' + argument2
  }
  return argument1 + '[' + argument2 + '] = ' + argument3
}

// 生成获取列表中某个元素的代码
pythonGenerator.forBlock['lists_get'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  let argument2 = generator.valueToCode(block, 'AT', Order.NONE) || '1'
  if (block.getFieldValue('WHERE') === 'FROM_START') {
    argument2 = isInteger(argument2) ? Number(argument2) - 1 : argument2 + ' - 1'
  } else if (block.getFieldValue('WHERE') === 'FROM_END') {
    argument2 = argument1 + '.length - ' + argument2
  }
  return [argument1 + '[' + argument2 + ']', Order.NONE]
}

// 生成获取列表中某个元素索引的代码
pythonGenerator.forBlock['lists_index'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  const argument2 = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"
  let code
  if (block.getFieldValue('WHERE') === 'FROM_START') {
    code = argument1 + '.index(' + argument2 + ') + 1'
  } else if (block.getFieldValue('WHERE') === 'FROM_END') {
    code = argument1 + '.rindex(' + argument2 + ') + 1'
  }
  return [code, Order.NONE]
}

// 生成判断列表中是否包含某个元素的代码
pythonGenerator.forBlock['lists_includes'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  const argument2 = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"
  return [argument1 + '.count(' + argument2 + ') > 0', Order.NONE]
}

// 生成获取列表长度的代码
pythonGenerator.forBlock['lists_length'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'LIST', Order.NONE) || '[]'
  return [argument1 + '.length', Order.NONE]
}

// time_current
pythonGenerator.forBlock['time_current'] = function () {
  return ['time.time()', Order.NONE]
}

//time_timestamp_to_date
pythonGenerator.forBlock['time_timestamp_to_date'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'TIMESTAMP', Order.NONE) || '0'
  return [
    'datetime.datetime.fromtimestamp(' + argument1 + ').strftime("%Y-%m-%d %H:%M:%S")',
    Order.NONE
  ]
}

pythonGenerator.forBlock['time_import'] = function () {
  return 'import time\n'
}

// http_get
pythonGenerator.forBlock['http_import'] = function () {
  return 'import requests\n'
}

pythonGenerator.forBlock['http_get'] = function (block, generator) {
  const URL = generator.valueToCode(block, 'URL', Order.NONE) || "''"
  const HEADERS = generator.valueToCode(block, 'HEADERS', Order.NONE) || '{}'
  const COOKIES = generator.valueToCode(block, 'COOKIES', Order.NONE) || '{}'
  return ['requests.get(' + URL + ', headers=' + HEADERS + ', cookies=' + COOKIES + ')', Order.NONE]
}

// http_post
pythonGenerator.forBlock['http_post'] = function (block, generator) {
  const URL = generator.valueToCode(block, 'URL', Order.NONE) || "''"
  const HEADERS = generator.valueToCode(block, 'HEADERS', Order.NONE) || '{}'
  const COOKIES = generator.valueToCode(block, 'COOKIES', Order.NONE) || '{}'
  const DATA = generator.valueToCode(block, 'DATA', Order.NONE) || '{}'
  return [
    'requests.post(' +
    URL +
    ', headers=' +
    HEADERS +
    ', cookies=' +
    COOKIES +
    ', data=' +
    DATA +
    ')',
    Order.NONE
  ]
}

// 设置空字典
pythonGenerator.forBlock['dict_create'] = function () {
  return ['dict()', Order.NONE]
}

// 设置字典
pythonGenerator.forBlock['dict_set'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'KEY', Order.NONE) || "''"
  const argument2 = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"
  const argument3 = generator.valueToCode(block, 'DICT', Order.NONE) || '{}'
  return argument3 + '[' + argument1 + '] = ' + argument2 + '\n'
}

//设置字典键
pythonGenerator.forBlock['set_dict'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'KEY', Order.NONE) || "''"
  const argument2 = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"

  //return argument2 + '[' + argument1 + '] = ' + argument2;
  return '{' + argument1 + ':' + argument2 + '}'
}

// 获取字典值
pythonGenerator.forBlock['dict_get'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'KEY', Order.NONE) || "''"
  const argument2 = generator.valueToCode(block, 'DICT', Order.NONE) || '{}'
  console.log(Order.NONE)
  return [argument2 + '[' + argument1 + ']', Order.NONE]
}

// 输出控制台
pythonGenerator.forBlock['console_log'] = function (block, generator) {
  const argument1 = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"
  return 'print(' + argument1 + ')\n'
}

// SQLite
//sqlite_open
pythonGenerator.forBlock['sqlite_import'] = function () {
  return 'import sqlite3\n'
}

pythonGenerator.forBlock['sqlite_open'] = function (block, generator) {
  const DB_NAME = generator.valueToCode(block, 'DATABASE', Order.NONE) || "''"
  return ['sqlite3.connect(' + DB_NAME + ')', Order.NONE]
}

//sqlite_query
pythonGenerator.forBlock['sqlite_query'] = function (block, generator) {
  const dbVar = generator.valueToCode(block, 'DB', Order.ATOMIC) || 'db';
  const sql = generator.valueToCode(block, 'SQL', Order.ATOMIC) || "''";
  return [
    `${dbVar}.cursor().execute(${sql}).fetchall()`,
    Order.FUNCTION_CALL
  ];
};

//sqlite_exec
pythonGenerator.forBlock['sqlite_exec'] = function (block, generator) {
  const dbVar = generator.valueToCode(block, 'DB', Order.ATOMIC) || 'db';
  const sql = generator.valueToCode(block, 'SQL', Order.ATOMIC) || "''";
  return `${dbVar}.cursor().execute(${sql})\n` + 
         `${dbVar}.commit()\n`;
};

//sqlite_close 
pythonGenerator.forBlock['sqlite_close'] = function (block, generator) {
  const dbVar = generator.valueToCode(block, 'DB', Order.ATOMIC) || 'db';
  return `${dbVar}.close()\n`;
};

// 在现有生成器代码后添加 JSON 处理逻辑
pythonGenerator.forBlock['json_parse'] = function (block, generator) {
  const value_json_string = generator.valueToCode(block, 'JSON_STRING', generator.ORDER_ATOMIC);
  return [`json.loads(${value_json_string})`, generator.ORDER_FUNCTION_CALL];
};

pythonGenerator.forBlock['json_stringify'] = function (block, generator) {
  let dictEntries = [];
  for (let i = 0; i < block.itemCount_; i++) {
    const key = generator.valueToCode(block, `KEY${i}`, generator.ORDER_NONE);
    const value = generator.valueToCode(block, `VALUE${i}`, generator.ORDER_NONE);
    dictEntries.push(`${key}: ${value}`);
  }
  return [`json.dumps({${dictEntries.join(', ')}})`, generator.ORDER_FUNCTION_CALL];
};

pythonGenerator.forBlock['json_merge'] = function (block, generator) {
  const json1 = generator.valueToCode(block, 'JSON1', generator.ORDER_ATOMIC);
  const json2 = generator.valueToCode(block, 'JSON2', generator.ORDER_ATOMIC);
  return [`{**${json1}, **${json2}}`, generator.ORDER_FUNCTION_CALL];
};

// 修改Base64生成器代码
pythonGenerator.forBlock['text_base64_encode'] = function(block, { valueToCode }) {
  const text = valueToCode(block, 'TEXT', Order.ATOMIC);
  return [`base64.b64encode(${text}.encode()).decode()`, Order.FUNCTION_CALL];
};

pythonGenerator.forBlock['text_base64_decode'] = function(block, { valueToCode }) {
  const base64Str = valueToCode(block, 'BASE64', Order.ATOMIC);
  return [`base64.b64decode(${base64Str}).decode()`, Order.FUNCTION_CALL];
};

// 修改JSON生成器部分保持风格一致
pythonGenerator.forBlock['json_to_base64'] = function(block, { valueToCode }) {
  const dictValue = valueToCode(block, 'DICT', Order.ATOMIC);
  return [`base64.b64encode(json.dumps(${dictValue}).encode()).decode()`, Order.FUNCTION_CALL];
};

// 引入base64模块
pythonGenerator.forBlock['base64_import'] = function() {
  return 'import base64\n';
};

// 新增文件写入积木生成器
pythonGenerator.forBlock['file_write'] = function(block, generator) {
  const file = generator.valueToCode(block, 'FILE', Order.ATOMIC);
  const content = generator.valueToCode(block, 'CONTENT', Order.NONE) || "''";
  return `${file}.write(str(${content}))\n`;
};

// 保持字典生成器参数解构风格
pythonGenerator.forBlock['dict_create'] = function(block, { valueToCode }) {
  // 新版字典生成逻辑
  if (block.getInput('PAIRS')) {
    let code = '{';
    let currentPair = block.getInputTargetBlock('PAIRS');

    while (currentPair) {
      const key = valueToCode(currentPair, 'KEY', Order.NONE);
      const value = valueToCode(currentPair, 'VALUE', Order.NONE);
      code += `${key}: ${value}, `;
      currentPair = currentPair.getNextBlock();
    }

    code = code.replace(/, $/, '') + '}';
    return [code, Order.ATOMIC];
  }

  // 旧版空字典实现
  return ['dict()', Order.NONE];
};
// 在json_to_base64生成器之后添加
pythonGenerator.forBlock['md5_hash'] = function(block, { valueToCode }) {
  const text = valueToCode(block, 'TEXT', Order.ATOMIC);
  return [`hashlib.md5(${text}.encode()).hexdigest()`, Order.FUNCTION_CALL];
};

pythonGenerator.forBlock['md5_import'] = function() {
  return 'import hashlib\n';
};

// 添加生成器逻辑
pythonGenerator.forBlock['file_open'] = function(block, generator) {
  const filename = generator.valueToCode(block, 'FILENAME', Order.ATOMIC);
  const mode = block.getFieldValue('MODE');
  return [`open(${filename}, '${mode}')`, Order.FUNCTION_CALL];
};

pythonGenerator.forBlock['file_read'] = function(block, generator) {
  const file = generator.valueToCode(block, 'FILE', Order.ATOMIC);
  return [`${file}.read()`, Order.FUNCTION_CALL];
};

pythonGenerator.forBlock['threading_import'] = function() {
  return 'import threading\n';
};

pythonGenerator.forBlock['threading_create'] = function(block, generator) {
  const name = generator.valueToCode(block, 'NAME', Order.NONE) || "'thread'";
  const func = generator.statementToCode(block, 'FUNCTION');
  
  return `def ${name}_func():\n${func}\n` +
         `${name} = threading.Thread(target=${name}_func)\n`;
};

pythonGenerator.forBlock['threading_start'] = function(block, generator) {
  const thread = generator.valueToCode(block, 'THREAD', Order.NONE) || 'thread';
  return `${thread}.start()\n`;
};

pythonGenerator.forBlock['threading_join'] = function(block, generator) {
  const thread = generator.valueToCode(block, 'THREAD', Order.NONE) || 'thread';
  return `${thread}.join()\n`;
};

pythonGenerator.forBlock['queue_create'] = function () {
  return ['queue.Queue()', Order.NONE];
};

pythonGenerator.forBlock['queue_import'] = function () {
  return 'import queue\n';
};

pythonGenerator.forBlock['queue_enqueue'] = function (block, generator) {
  const item = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
  const queue = generator.valueToCode(block, 'QUEUE', Order.NONE) || 'queue.Queue()';
  return queue + '.put(' + item + ')';
};

pythonGenerator.forBlock['queue_dequeue'] = function (block, generator) {
  const queue = generator.valueToCode(block, 'QUEUE', Order.NONE) || 'queue.Queue()';
  return [queue + '.get()', Order.NONE];
};

pythonGenerator.forBlock['queue_is_empty'] = function (block, generator) {
  const queue = generator.valueToCode(block, 'QUEUE', Order.NONE) || 'queue.Queue()';
  return [queue + '.empty()', Order.NONE];
};
pythonGenerator.forBlock['http_response_text'] = function(block, generator) {
  const response = generator.valueToCode(block, 'RESPONSE', Order.ATOMIC) || 'response';
  return [`${response}.text`, Order.NONE];
};

